import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';

import { appRoutes } from './routes';
import { REDIRECT_MAIN, NOT_FOUND_ROUTE } from './routes/base';
import createRouteGuard from './guard';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: 'login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    ...appRoutes,
    REDIRECT_MAIN,
    NOT_FOUND_ROUTE,
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});

// 添加动态路由的方法
export function addDynamicRoutes(routes: any[]) {
  console.log('添加动态路由:', routes);

  // 定义组件映射
  const componentMap: Record<string, any> = {
    // 布局组件
    'Layout': () => import('@/layout/default-layout.vue'),
    'default-layout': () => import('@/layout/default-layout.vue'),

    // 仪表盘
    'dashboard/workplace/index': () =>
      import('@/views/dashboard/workplace/index.vue'),
    'dashboard/monitor/index': () =>
      import('@/views/dashboard/monitor/index.vue'),

    // 系统管理
    'system/menu/index': () => import('@/views/system/menu/index.vue'),
    'system/user/index': () => import('@/views/system/user/index.vue'),
    'system/role/index': () => import('@/views/system/role/index.vue'),

    // 平台管理
    'forward/server/index': () => import('@/views/forward/server/index.vue'),

    // 站点管理
    'station/car/index': () => import('@/views/station/car/index.vue'),

    // 充电管理
    'charging/order/index': () => import('@/views/charging/order/index.vue'),
    'charging/refund/index': () => import('@/views/charging/refund/index.vue'),

    // 合作伙伴管理
    'partner/index': () => import('@/views/partner/index.vue'),
    'partner/station': () => import('@/views/partner/station.vue'),
    'partner/withdraw/index': () =>
      import('@/views/partner/withdraw/index.vue'),
    'station/device/index': () => import('@/views/station/device/index.vue'),
    'station/device/forward-log': () =>
      import('@/views/station/device/forward-log.vue'),
    'station/pile/index': () => import('@/views/station/pile/index.vue'),
    'platform/index': () => import('@/views/platform/index.vue'),
    'partner/deposit/index': () => import('@/views/partner/deposit/index.vue'),
    'order/reconciliation/index': () =>
      import('@/views/order/reconciliation/index.vue'),
    'order/sync-reconciliation/index': () =>
      import('@/views/order/sync-reconciliation/index.vue'),
    'charging/list/index': () => import('@/views/charging/list/index.vue'),
    'car/charging/group/index': () =>
      import('@/views/car/charging/group/index.vue'),
    'profit/template/index': () => import('@/views/profit/template/index.vue'),
  };

  try {
    routes.forEach((route) => {
      // 避免重复添加
      if (!router.hasRoute(route.name)) {
        // 处理组件
        if (typeof route.component === 'string') {
          const componentPath = route.component;
          // 移除开头的斜杠
          const normalizedPath = componentPath.startsWith('/')
            ? componentPath.substring(1)
            : componentPath;

          console.log(`处理组件路径: ${componentPath} -> ${normalizedPath}`);

          // 查找组件映射
          if (componentMap[normalizedPath]) {
            route.component = componentMap[normalizedPath];
            console.log(`找到组件映射: ${normalizedPath}`);
          } else {
            console.warn(`未找到组件映射: ${normalizedPath}，尝试动态导入`);
            try {
              route.component = () => import(`@/views/${normalizedPath}.vue`);
            } catch (e) {
              console.error(`无法导入组件: @/views/${normalizedPath}.vue`, e);
            }
          }
        }

        // 处理子路由
        if (route.children && route.children.length > 0) {
          route.children.forEach((child: any) => {
            if (typeof child.component === 'string') {
              const componentPath = child.component;
              // 移除开头的斜杠
              const normalizedPath = componentPath.startsWith('/')
                ? componentPath.substring(1)
                : componentPath;

              console.log(
                `处理子路由组件路径: ${componentPath} -> ${normalizedPath}`
              );

              // 查找组件映射
              if (componentMap[normalizedPath]) {
                child.component = componentMap[normalizedPath];
                console.log(`找到子路由组件映射: ${normalizedPath}`);
              } else {
                console.warn(
                  `未找到子路由组件映射: ${normalizedPath}，尝试动态导入`
                );
                try {
                  child.component = () =>
                    import(`@/views/${normalizedPath}.vue`);
                } catch (e) {
                  console.error(
                    `无法导入子路由组件: @/views/${normalizedPath}.vue`,
                    e
                  );
                }
              }
            }
          });
        }

        // 添加路由
        router.addRoute(route);
        console.log(`成功添加路由: ${route.name}, 路径: ${route.path}`);
      }
    });

    // 打印所有路由
    console.log(
      '当前所有路由:',
      router.getRoutes().map((r) => ({
        name: r.name,
        path: r.path,
        children: r.children?.map((c) => ({ name: c.name, path: c.path })),
      }))
    );
  } catch (error) {
    console.error('添加动态路由失败:', error);
  }
}

createRouteGuard(router);

export default router;
